package com.atguigu.day72_demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareData {
    int number = 1;
    private final Lock lock = new ReentrantLock();
    private final Condition notFull1 = lock.newCondition();
    private final Condition notFull2 = lock.newCondition();
    private final Condition notFull3 = lock.newCondition();

    public void println5() {
        lock.lock();
        try {
            while (number != 1) {
                notFull1.await();
            }
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + "====" + "AA打印第:" + i + "次");
                number = 2;
                notFull2.signal();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void println10() {
        lock.lock();
        try {
            while (number != 2) {
                notFull2.await();
            }
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName() + "====" + "BB打印第:" + i + "次");
                number = 3;
                notFull3.signal();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void println15() {
        lock.lock();
        try {
            while (number != 3) {
                notFull3.await();
            }
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName() + "====" + "CC打印第:" + i + "次");
                number = 1;
                notFull1.signal();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}


/**
 * @auther zzyy
 * @create 2024-08-06 8:34
 * 线程间定制化调用通信
 * <p>
 * * 多线程之间按顺序调用，实现A->B->C
 * * 三个线程启动，要求如下：
 * *
 * * AA打印5次，BB打印10次，CC打印15次
 * * 接着
 * * AA打印5次，BB打印10次，CC打印15次
 * * ......来10轮
 */
public class ThreadOrderAccess {
    public static void main(String[] args) {
        ShareData data = new ShareData();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                data.println5();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                data.println10();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                data.println15();
            }
        }, "C").start();
    }
}


